package com.tebiecloud.yunst.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tebiecloud.common.mybatis.base.service.impl.BaseServiceImpl;
import com.tebiecloud.common.utils.HttpClient;
import com.tebiecloud.common.utils.JsoupHttpClientUtils;
import com.tebiecloud.common.utils.StringUtils;
import com.tebiecloud.yunst.client.model.entity.YunStUser;
import com.tebiecloud.yunst.server.mapper.YunStUserMapper;
import com.tebiecloud.yunst.server.service.YunStUserService;
import com.tebiecloud.yunst.server.utils.UrlUtils;
import com.tebiecloud.yunst.server.yunstservice.YunStService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * 云商通用户表 服务实现类
 * @author tebie
 * @date 2019-09-07
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class YunStUserServiceImpl extends BaseServiceImpl<YunStUserMapper, YunStUser> implements YunStUserService {

    @Value("${tebiecloud.yunst.jumpUrl}")
    private String jumpUrl;

    @Value("${tebiecloud.yunst.backUrl}")
    private String backUrl;

    @Value("${tebiecloud.yunst.urlTager}")
    private String urlTager;

    @Autowired
    YunStService yunStService;

    @Autowired
    YunStUserMapper yunStUserMapper;

    @Override
    public Map<String,String> realName(YunStUser entity) {
        Map<String,String> resultMap =  yunStService.setRealName(entity.getBizUserId(),entity.getName(),entity.getIdentityNo());
        if(resultMap.get("status").equals("OK")){
            QueryWrapper<YunStUser> queryWrapper = new QueryWrapper<YunStUser>();
            queryWrapper.eq("biz_user_id",entity.getBizUserId());
            yunStUserMapper.update(entity,queryWrapper);
        }
        return resultMap;
    }

    @Override
    public Map<String, String> applyBindAcct(String bizUserId, String acctType, String acct) {
        Map<String,String> resultMap =  yunStService.applyBindAcct(bizUserId,acctType,acct);
        if(resultMap.get("status").equals("OK")){
            QueryWrapper<YunStUser> queryWrapper = new QueryWrapper<YunStUser>();
            queryWrapper.eq("biz_user_id",bizUserId);
            YunStUser entity = new YunStUser();
            entity.setAcct(acct);
            yunStUserMapper.update(entity,queryWrapper);
        }
        return resultMap;
    }

    @Override
    public Map<String,String> signContract(String bizUserId) {
        Map<String,String> resultMap = new HashMap<String,String>();
        //查询是否已经电子签约
        Map<String,String> map = yunStService.getMemberInfo(bizUserId);
        //查询这边的数据
        QueryWrapper<YunStUser> yunStUserQueryWrapper = new QueryWrapper<>();
        yunStUserQueryWrapper.eq("biz_user_id",bizUserId);
        YunStUser yunStUser = yunStUserMapper.selectOne(yunStUserQueryWrapper);
        if(map.get("status").equals("OK")){
            if(map.get("isSignContract").equals("true")){
                resultMap.put("status","OK");
                if(yunStUser!=null && yunStUser.getSignContract().equals(0)){
                    UpdateWrapper<YunStUser> yunStUserUpdateWrapper = new UpdateWrapper<YunStUser>();
                    yunStUserUpdateWrapper.eq("biz_user_id",bizUserId);
                    YunStUser yunStUser1 = new YunStUser();
                    yunStUser1.setSignContract(1);
                    yunStUserMapper.update(yunStUser1,yunStUserUpdateWrapper);
                }
            }else{
                //获取签约链接
                String signJumpUrl = jumpUrl+"/yunst/yunstuser/signcontract/update";
                String signBackUrl = backUrl+"/yunst/yunstuser/signcontract/update";
                String url = yunStService.signContract(bizUserId,signJumpUrl,signBackUrl);
                String sysid = UrlUtils.parse(url).params.get("sysid");
                HttpClient httpClient = new HttpClient();
                String params = "/service/soa/MemberServlet.do?sysid=" + sysid + "&jumpUrl=" + signJumpUrl + "&backUrl=" + signBackUrl +
                        "&bizUserId=" +bizUserId + "&source=2&action=signContract";
                String reslut = httpClient.GET(urlTager+params);
                if(JSON.parseObject(reslut).get("status").equals("OK")){
                    resultMap.put("status","OK");
                    if(yunStUser.getSignContract().equals(0)){
                        //更新签约状态
                        UpdateWrapper<YunStUser> yunStUserUpdateWrapper = new UpdateWrapper<>();
                        yunStUserUpdateWrapper.eq("biz_user_id",bizUserId);
                        YunStUser yunStUser1 = new YunStUser();
                        yunStUser1.setSignContract(1);
                        yunStUserMapper.update(yunStUser1,yunStUserUpdateWrapper);
                    }
                }else{
                    resultMap.put("status","error");
                    resultMap.put("message","签约失败");
                }
            }
        }else{
            resultMap.put("status",map.get("status"));
            resultMap.put("message",map.get("message"));
        }
        return resultMap;
    }

    @Override
    public Map<String, String> sendVerificationCode(String bizUserId,String phone) {
        Map<String, String> resultMap = yunStService.sendVerificationCode(bizUserId,phone,null);
        return resultMap;
    }

    @Override
    public Map<String, String> bindPhone(String bizUserId, String phone, String verificationCode) {
        Map<String, String> resultMap = yunStService.bindPhone(bizUserId,phone,verificationCode);
        return resultMap;
    }

    @Override
    public Map<String, Object> createOrUpdate(Long userId,String acctType,String openId) {
        Map<String, Object> resultMap = new HashMap<String,Object>();
        //查询是否有用户
        QueryWrapper<YunStUser> yunStUserQueryWrapper = new QueryWrapper<>();
        yunStUserQueryWrapper.eq("user_id",userId);
        YunStUser yunStUser = yunStUserMapper.selectOne(yunStUserQueryWrapper);
        if(yunStUser==null){
            String bizUserId = yunStService.createMember(null,"3","1");
            if(bizUserId.equals("0")) {
                resultMap.put("status","error");
                resultMap.put("message","创建用户失败");
                return resultMap;
            }
            yunStUser = new YunStUser();
            yunStUser.setBizUserId(bizUserId);
            yunStUser.setUserId(userId);
            yunStUser.setMemberType(3);
            yunStUser.setSource(1);
            yunStUser.setSignContract(0);
            yunStUserMapper.insert(yunStUser);
            //绑定openId
            Map<String,String> map =  yunStService.applyBindAcct(bizUserId,acctType,openId);
            if(map.get("status").equals("OK")){
                yunStUser.setAcct(openId);
                UpdateWrapper<YunStUser> yunStUserUpdateWrapper = new UpdateWrapper<>();
                yunStUserUpdateWrapper.eq("biz_user_id",bizUserId);
                yunStUserMapper.update(yunStUser,yunStUserUpdateWrapper);
            }else{
                resultMap.put("status","error");
                resultMap.put("message","绑定用户标识失败");
                return resultMap;
            }
        }else{
            //查询是否绑定openid
            if(StringUtils.isEmpty(yunStUser.getAcct())){
                //绑定openId
                Map<String,String> map =  yunStService.applyBindAcct(yunStUser.getBizUserId(),acctType,openId);
                if(map.get("status").equals("OK")){
                    yunStUser.setAcct(openId);
                    UpdateWrapper<YunStUser> yunStUserUpdateWrapper = new UpdateWrapper<>();
                    yunStUserUpdateWrapper.eq("biz_user_id",yunStUser.getBizUserId());
                    yunStUserMapper.update(yunStUser,yunStUserUpdateWrapper);
                    resultMap.put("status","OK");
                }else{
                    resultMap.put("status","error");
                    resultMap.put("message","绑定用户标识失败");
                    return resultMap;
                }
            }
        }
        resultMap.put("status","OK");
        resultMap.put("yunStUser",yunStUser);
        return resultMap;
    }

}
